//
//  MatchAboutUsViewController.m
//  us
//
//  Created by lhx on 2025/4/2.
//

#import "MatchAboutUsViewController.h"
#import "USDateAlertView.h"
@interface MatchAboutUsViewController ()

@property (nonatomic, strong)UIButton *doneBtn;

@property (nonatomic, strong)NSDate *birthDate;

@end

@implementation MatchAboutUsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setupView];
    
    [self editWithIndex:0];
    
  
    @weakify(self)
    RACSignal *birthdayValidSignal = [RACObserve(self, birthDate) map:^id _Nullable(NSDate *date) {
        return @(date != nil);
    }];
     [[RACSignal combineLatest:@[birthdayValidSignal, RACObserve(self.companionBtn, selected), RACObserve(self.friendfBtn, selected)]
                      reduce:^id(NSNumber *birthdayValid, NSNumber *femaleSelected, NSNumber *maleSelected) {
        return @(birthdayValid.boolValue && (femaleSelected.boolValue || maleSelected.boolValue));
    }]
     subscribeNext:^(NSNumber * _Nullable isEnabled) {
        @strongify(self);
        self.doneBtn.enabled = isEnabled.boolValue;
    }];
    
}

- (void)setupView {
    NSString *gifPath = [[NSBundle mainBundle] pathForResource:@"match_2" ofType:@"gif"];
    NSURL *fileURL = [NSURL fileURLWithPath:gifPath];
    [self.imgView sd_setImageWithURL:fileURL];
    
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.strokeColor = [UIColor jk_colorWithHex:0xEAEAE1].CGColor;
    shapeLayer.lineWidth = 2;
    shapeLayer.lineCap = kCALineCapRound;
    shapeLayer.lineDashPattern = @[@8, @8];

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(16, self.topBgView.jk_height - 2)];
    [path addLineToPoint:CGPointMake(ScreenWidth - 32, self.topBgView.jk_height - 2)];
    
    shapeLayer.path = path.CGPath;
    [self.topBgView.layer addSublayer:shapeLayer];
    
    
    [self.view addSubview:self.doneBtn];
    [self.doneBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(56);
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft).mas_offset(32);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight).mas_offset(-32);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-28);
    }];
    
    
}


- (void)addUserRelation {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    NSInteger type = 0;
    if (self.companionBtn.selected) {
        type = 1;
    }else if (self.friendfBtn.selected) {
        type = 2;
    }
    
    [params setValue:@(type) forKey:@"relType"];
    [params setValue:self.invitationCode forKey:@"invitationCode"];

    [params setValue:USUser.user.userId forKey:@"myselfUserId"];
    [params setValue:USUser.user.imUserName forKey:@"myselfImUserName"];
    [params setValue:USUser.user.imToken forKey:@"myselfImToken"];
    
    NSTimeInterval timestamp = [self.birthDate timeIntervalSince1970];
    NSString *birthday = [NSString stringWithFormat:@"%li",(NSInteger)timestamp];
    [params setValue:birthday forKey:@"metTime"];

    
    [[EMNetWork shareManager]em_post:API_AddUserRelation params:params hud:@"" showError:YES success:^(EMApiModel *api) {
        if (api.success == NO) {
            return;
        }
        //匹配成功后重新登录环信（因为在接触匹配时退出了环信）
        [[EMClient sharedClient] loginWithUsername:USUser.user.imUserName token:USUser.user.imToken completion:^(NSString * _Nonnull aUsername, EMError * _Nullable aError) {
            if (aError) {
                NSLog(@"环信登录失败 ---- %li,%@",aError.code,aError);

            }else {
                NSLog(@"环信登录成功");
            }
        }];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:USNotificationMatch object:nil];

        [self.view endEditing:YES];

        [self.navigationController popToRootViewControllerAnimated:YES];

     
    } fail:^{
        
    }];
}
- (IBAction)companionAction:(id)sender {
    self.companionBtn.selected = YES;
    self.friendfBtn.selected = NO;
    [self editWithIndex:1];
}

- (IBAction)friendAction:(id)sender {
    self.companionBtn.selected = NO;
    self.friendfBtn.selected = YES;
    [self editWithIndex:1];
}

- (IBAction)dateAction:(id)sender {
    [self editWithIndex:2];

    USDateAlertView *alert = [[USDateAlertView alloc]initWithDate:[NSDate date] andSubTitle:@"设置我们认识的日子" limitToNow:YES];
    [alert showInView:UIViewController.topViewController.view];
    @weakify(self)
    alert.didChooseBlock = ^(NSDate * _Nonnull date) {
        @strongify(self)
        self.birthDate = date;
        NSString * dateString = [date jk_dateWithFormat:@"YYYY/MM/dd"];
        [self.dateBtn setTitleColor:UIColor.titleColor forState:0];
        [self.dateBtn setTitle:dateString forState:0];
    };
}


- (void)editWithIndex:(NSInteger)index {
  
    if (index == 0) {
        self.companionBgView.layer.borderColor = UIColor.clearColor.CGColor;
        self.dateBgView.layer.borderColor = UIColor.clearColor.CGColor;
    }else if (index == 1) {
         self.companionBgView.layer.borderColor = UIColor.brightBorderColor.CGColor;
        self.dateBgView.layer.borderColor = UIColor.clearColor.CGColor;
    }else if (index == 2) {
         self.companionBgView.layer.borderColor = UIColor.clearColor.CGColor;
        self.dateBgView.layer.borderColor = UIColor.brightBorderColor.CGColor;
    }
}

- (UIButton *)doneBtn {
    if (_doneBtn == nil) {
        _doneBtn = [UIButton us_fillButtonWithTitle:@"完成啦"];
        _doneBtn.layer.cornerRadius = 14;
        [_doneBtn addTarget:self action:@selector(addUserRelation) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneBtn;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
